
var Menubar = function () {
    var container = $('<div class="Panel"></div>');

    var root = $('<ul id="menu"></ul>');

    Menubar.Project(root);
    Menubar.Config(root);
    Menubar.Tools(root);
    Menubar.Settings(root);

    container.add(root.menu());

    $(document.body).append(container.node);
    container.css('zIndex', 2);
};

Menubar.Project = function (root) {
    var mProject = root.sub(halo_i18n.s9);

    if (window.editor_type === 'desktop') {
        mProject.sub('Open').bind('click', function () {
            let value = ipcRenderer.sendSync('project-open');
            if (value !== '') {
                ipcRenderer.sendSync('reload');
            }
        });
    }

    function fake_click(obj) {
        var ev = document.createEvent("MouseEvents");
        ev.initMouseEvent(
            "click", true, false, window, 0, 0, 0, 0, 0
            , false, false, false, false, 0, null
        );
        obj.dispatchEvent(ev);
    }

    function download(text, name, type) {
        var a = document.createElement("a");
        var file = new Blob([text], { type: type });
        a.href = URL.createObjectURL(file);
        a.download = name;
        fake_click(a);
    }

    // Export
    var iExport = mProject.sub('Export');

    iExport.sub('Batches').bind('click', function () {
        Editor.encodeProject(function (data) {
            var zip = new JSZip();
            var filename = (Halo.Config.get().name || Halo.Math.genName()) + '.halo';
            zip.file(filename, data);
            var content = zip.generate({
                type: "uint8array",
                compression: "DEFLATE",
                compressionOptions: {
                    level: 9
                }
            });
            download(content, filename, 'text/plain');
        });
    });

    iExport.sub('All').bind('click', function () {
        Editor.encodeAssets(function (data) {
            var zip = new JSZip();
            var filename = (Halo.Config.get().name || Halo.Math.genName()) + '.halo';
            zip.file(filename, data);
            var content = zip.generate({
                type: "uint8array",
                compression: "DEFLATE",
                compressionOptions: {
                    level: 9
                }
            });
            download(content, filename, 'text/plain');
        });
    });

    // Import
    mProject.sub('Import').bind('click', function () {
        var fileInput = document.createElement('input');
        document.body.appendChild(fileInput);
        fileInput.type = 'file';
        fileInput.value = '';
        fileInput.addEventListener('change', function (event) {
            var file = fileInput.files[0];
            var extension = file.name.split('.').pop().toLowerCase();
            console.log('filename', file.name);
            document.body.removeChild(fileInput);

            var reader = new FileReader();
            reader.onload = function () {
                var data = new Uint8Array(reader.result);
                var meta = Halo.ResourceManager.unzip(data);

                Halo.ResourceManager.clearCache();
                Halo.parseProject(meta, function (res) {
                    if (res === null) {
                        Editor.Signal_Project.dispatch();
                        if (window.editor_type === 'desktop') {
                            Editor.save_project(meta);
                        }
                    }
                });
            };
            reader.readAsArrayBuffer(file);
        });
        console.log('input value', fileInput.value);
        fileInput.click();
    });

    // Upload
    if (window.editor_type === 'web') {
        function uploadProject() {
            var filename = window.asset_id !== null ? window.asset_id : '0';
            Editor.encodeProject(function (data) {
                var zip = new JSZip();
                zip.file(filename, data);
                var content = zip.generate({
                    type: "uint8array",
                    compression: "DEFLATE",
                    compressionOptions: {
                        level: 9
                    }
                });

                var formData = new FormData();
                var blob = new Blob([content], { type: 'text/plain' });
                formData.append('asset', blob, filename + '.halo');
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/web/vrshop/file/updateModelFile', true);
                xhr.upload.onprogress = function (evt) {
                    if (evt.lengthComputable) {
                        Editor.Signal_UpdateProgress.dispatch('Uploading: ' + evt.loaded + '/' + evt.total);
                    }
                };
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        Editor.Signal_UpdateProgress.dispatch('Uploading: Finish');
                        alert('Response: \n' + xhr.responseText);
                    }
                };
                xhr.send(formData);

                // /web/vrshop/model/updateModel?modelId=13541&faceCount=333&vertexCount=222
            });
        }

        function uploadScreenShot() {
            var filename = window.asset_id !== null ? window.asset_id : '0';
            var screenshot = window.viewport.screenshot().replace(/^data:.*;base64,/, "");
            var content = Halo.base64ToUint8Array(screenshot);
            var blob = new Blob([content], { type: 'text/plain' });
            var formData = new FormData();
            formData.append('asset', blob, filename + '.png');
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/web/vrshop/file/updateModelFrontUrl', true);
            xhr.upload.onprogress = function (evt) {
                if (evt.lengthComputable) {
                    Editor.Signal_UpdateProgress.dispatch('Uploading: ' + evt.loaded + '/' + evt.total);
                }
            };
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    Editor.Signal_UpdateProgress.dispatch('Uploading: Finish');
                    alert('Response: \n' + xhr.responseText);
                }
            };
            xhr.send(formData);
        }

        var iUpload = mProject.sub('Upload');

        iUpload.sub('Project').bind('click', uploadProject);
        iUpload.sub('Front Image').bind('click', uploadScreenShot);
    }

    // Play
    mProject.sub('Play').bind('click', function () {
        if (window.editor_type === 'desktop') {
            ipcRenderer.send('play', true, false);
        } else {
            Editor.encodeProject(function (data) {
                var zip = new JSZip();
                var filename = window.asset_id !== null ? window.asset_id : '0';
                zip.file(filename, data);
                var content = zip.generate({
                    type: "uint8array",
                    compression: "DEFLATE",
                    compressionOptions: {
                        level: 9
                    }
                });

                Halo.Storage.set(window.asset_id, content, 0);

                window.open("player.html?id=" + window.asset_id);
            });
        }
    });

    //debug
    if (window.editor_type === 'desktop') {
        var iDebug = mProject.sub('Debug');

        iDebug.sub('Main Batch').bind('click', function () {
            ipcRenderer.send('play', false, true);
        });

        iDebug.sub('All').bind('click', function () {
            ipcRenderer.send('play', true, true);
        });
    }
};

Menubar.Config = function (root) {
    root.sub(halo_i18n.s10).bind('click', function () {
        Editor.Signal_Asset.dispatch('', 'config.json');
    });
};

// var serverPanel = new UI.Modal();
// serverPanel.container.css('width', '200px').css('height', '270px').css('text-align', 'center');
// var serverUrl = $('<p></p>');
// var serverQRCode = $('<div></div>');
// var qrcode = null;
// serverPanel.container.append(serverUrl, serverQRCode);
// $(document.body).append(serverPanel.node);


Menubar.Tools = function (root) {
    var iTools = root.sub(halo_i18n.s11);

    iTools.sub('Sprite Packer').bind('click', function () {
        PanelSpriter.show();
    });

    if (window.editor_type === 'desktop') {
        //Refresh Version
        iTools.sub('Refresh Version').bind('click', function () {
            var msg = ipcRenderer.sendSync('refresh-version');
            alert(msg);
        });

        iTools.sub('Reload Window').bind('click', function () {
            ipcRenderer.sendSync('reload');
        });

        iTools.sub('Debug Tool').bind('click', function () {
            ipcRenderer.send('debugtool');
        });

        var iServer = iTools.sub('Server');

        iServer.sub('Open').bind('click', function () {
            Editor.encodeAssets(function (data) {
                var zip = new JSZip();
                var filename = 'test.halo';
                zip.file(filename, data);
                var content = zip.generate({
                    type: "uint8array",
                    compression: "DEFLATE",
                    compressionOptions: {
                        level: 9
                    }
                });

                var playfolder = ipcRenderer.sendSync('play-folder');
                ipcRenderer.sendSync('save_file', { filename: playfolder + '/' + filename, data: content, base64: false });

                var url = ipcRenderer.sendSync('server', 'open');
                if (!qrcode) {
                    qrcode = new QRCode(serverQRCode.get(0), {
                        text: url,
                        width: 200,
                        height: 200,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.H
                    });
                }
                serverUrl.html(url);
                qrcode.clear();
                qrcode.makeCode(url);
                serverPanel.css('display', 'block');
            });
        });

        iServer.sub('Close').bind('click', function () {
            alert(ipcRenderer.sendSync('server', 'close'));
        });
    }
};

Menubar.Settings = function (root) {
    var iSettings = root.sub(halo_i18n.s12);

    var iTheme = iSettings.sub('Theme');

    iTheme.sub('Light').bind('click', function () {
        Editor.setTheme('light');
    });

    iTheme.sub('Dark').bind('click', function () {
        Editor.setTheme('dark');
    });

    var iLanguage = iSettings.sub('Lang');

    iLanguage.sub('English').bind('click', function () {
        if (window.editor_type === 'desktop') {
            ipcRenderer.sendSync('language', 'EN');
            ipcRenderer.sendSync('reload');
        }
    });

    iLanguage.sub('中文').bind('click', function () {
        if (window.editor_type === 'desktop') {
            ipcRenderer.sendSync('language', 'CN');
            ipcRenderer.sendSync('reload');
        }
    });
};
